/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.dataprovider.view.wizard.wizard;

import com.compomics.dataprovider.control.GUIExecutor;
import com.compomics.util.gui.waiting.waitinghandlers.WaitingDialog;
import java.awt.CardLayout;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author Kenneth
 */
public class FastaCreationWizard extends javax.swing.JPanel {

    private final LinkedList<JPanel> cardMapping = new LinkedList<>();
    private int currentSelectedIndex = 0;
    private boolean reset = false;

    /**
     * Creates new form FastaCreationWizard
     */
    public FastaCreationWizard() {
        initComponents();
        cardMapping.add(inputMethodPanel1);
        cardMapping.add(inputFilePanel1);
        cardMapping.add(inputTaxonomyPanel1);
        cardMapping.add(outputFilePanel1);
        cardMapping.add(processingMethodPanel1);
    }

    public void reset() {
        inputMethodPanel1.reset();
        inputFilePanel1.reset();
        inputTaxonomyPanel1.reset();
        outputFilePanel1.reset();
        processingMethodPanel1.reset();
        CardLayout layout = (CardLayout) jPanel1.getLayout();
        layout.first(jPanel1);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        rbInputButtonGroup = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        inputMethodPanel1 = new com.compomics.dataprovider.view.wizard.panels.input.InputMethodPanel();
        inputFilePanel1 = new com.compomics.dataprovider.view.wizard.panels.input.InputFilePanel();
        inputTaxonomyPanel1 = new com.compomics.dataprovider.view.wizard.panels.input.InputTaxonomyPanel();
        processingMethodPanel1 = new com.compomics.dataprovider.view.wizard.panels.processing.ProcessingMethodPanel();
        outputFilePanel1 = new com.compomics.dataprovider.view.wizard.panels.output.OutputFilePanel();
        btnNext = new javax.swing.JButton();
        btnBack = new javax.swing.JButton();

        setBackground(null);
        setMaximumSize(new java.awt.Dimension(450, 230));
        setMinimumSize(new java.awt.Dimension(450, 230));
        setPreferredSize(new java.awt.Dimension(450, 230));

        jPanel1.setBackground(null);
        jPanel1.setLayout(new java.awt.CardLayout());
        jPanel1.add(inputMethodPanel1, "card3");
        jPanel1.add(inputFilePanel1, "card2");
        jPanel1.add(inputTaxonomyPanel1, "card4");
        jPanel1.add(processingMethodPanel1, "card5");
        jPanel1.add(outputFilePanel1, "card6");

        btnNext.setText("Next");
        btnNext.setName("Next"); // NOI18N
        btnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextActionPerformed(evt);
            }
        });

        btnBack.setText("Back");
        btnBack.setEnabled(false);
        btnBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBackActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnBack)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnNext)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNext)
                    .addComponent(btnBack))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextActionPerformed
        if (btnNext.getText().equalsIgnoreCase("OK")) {
            try {
                File outputFile = outputFilePanel1.getOutputFile();

                if (outputFile == null) {
                    JOptionPane.showMessageDialog(this,
                            "The output file can not be empty !",
                            "Inane error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                } else {
                    if (!outputFile.exists()) {
                        if (!outputFile.getName().toLowerCase().endsWith(".fasta")) {
                            outputFile = new File(outputFile.getPath() + ".fasta");
                        }
                        outputFile.getParentFile().mkdirs();
                        outputFile.createNewFile();
                    }
                }
                if (!inputFilePanel1.isSkipped() && inputFilePanel1.getSelectedFiles().isEmpty()) {
                    JOptionPane.showMessageDialog(this,
                            "The list of input files can not be empty !",
                            "Inane error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }
                if (!inputTaxonomyPanel1.isSkipped() && inputTaxonomyPanel1.getSelectedTaxonomies().isEmpty()) {
                    JOptionPane.showMessageDialog(this,
                            "The list of input taxonomies can not be empty !",
                            "Inane error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }
                //skip downloading if it's required...
                //TODO find an elegant solution for this
                List<String> selectedTaxonomies;
                if (inputMethodPanel1.getDownload()) {
                    selectedTaxonomies = inputTaxonomyPanel1.getSelectedTaxonomies();
                } else {
                    selectedTaxonomies = new ArrayList<>();
                }

                WaitingDialog dialog = new WaitingDialog(null, null, null, false, "Processing", "Compomics Fasta Provider", "", true);
                dialog.setLocationRelativeTo(null);
                GUIExecutor executor = new GUIExecutor(dialog);
                executor.setFilesToMerge(inputFilePanel1.getSelectedFiles());
                executor.setTaxonomiesToDownload(selectedTaxonomies);
                executor.setIsReviewOnly(inputTaxonomyPanel1.isReviewOnly());
                executor.setIsAppend(true);
                executor.setIsDecoy(processingMethodPanel1.isDecoys());
                executor.setIsCrap(processingMethodPanel1.isCrap());
                executor.setDeleteDuplicateAccessions(processingMethodPanel1.isDeleteDuplicateAccessions());
                executor.setDeleteDuplicateSequences(processingMethodPanel1.isDeleteDuplicateSequences());
                executor.setOutputFile(outputFile);
                reset = executor.execute();
                dialog.dispose();
                if (!reset) {
                    return;
                }
            } catch (IOException ex) {
                Logger.getLogger(FastaCreationWizard.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            goForward();
        }
    }//GEN-LAST:event_btnNextActionPerformed

    private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
        goBackward();
    }//GEN-LAST:event_btnBackActionPerformed

    private void goForward() {
        //update index
        CardLayout layout = (CardLayout) jPanel1.getLayout();
        if (currentSelectedIndex < cardMapping.size() - 1) {
            layout.next(jPanel1);
            currentSelectedIndex++;
            skipMethods(true);
        }
    }

    private void goBackward() {
        CardLayout layout = (CardLayout) jPanel1.getLayout();
        //update index
        if (currentSelectedIndex > 0) {
            layout.previous(jPanel1);
            currentSelectedIndex--;
            skipMethods(false);
        }
    }

    private void updateButtons() {
        if (currentSelectedIndex == 0) {
            btnBack.setEnabled(false);
        } else if (currentSelectedIndex == cardMapping.size() - 1) {
            btnNext.setText("OK");
            btnNext.setName("PROCESS");
        } else {
            btnNext.setText("Next");
            btnNext.setName("NEXT");
            btnNext.setEnabled(true);
            btnBack.setEnabled(true);
        }
    }

    private void skipMethods(boolean forward) {
        if (currentSelectedIndex == 1) {
            inputFilePanel1.setSkipped(false);
            inputTaxonomyPanel1.setSkipped(false);
            switch (inputMethodPanel1.getSelectedOption()) {
                case 1:
                    inputTaxonomyPanel1.setSkipped(true);
                    break;
                case 2:
                    inputFilePanel1.setSkipped(true);
                    break;
            }
        }
        if (currentSelectedIndex == 1 && inputFilePanel1.isSkipped()) {
            if (forward) {
                goForward();
            } else {
                goBackward();
            }
        }
        if (currentSelectedIndex == 2 && inputTaxonomyPanel1.isSkipped()) {
            if (forward) {
                goForward();
            } else {
                goBackward();
            }
        }
        updateButtons();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBack;
    private javax.swing.JButton btnNext;
    private com.compomics.dataprovider.view.wizard.panels.input.InputFilePanel inputFilePanel1;
    private com.compomics.dataprovider.view.wizard.panels.input.InputMethodPanel inputMethodPanel1;
    private com.compomics.dataprovider.view.wizard.panels.input.InputTaxonomyPanel inputTaxonomyPanel1;
    private javax.swing.JPanel jPanel1;
    private com.compomics.dataprovider.view.wizard.panels.output.OutputFilePanel outputFilePanel1;
    private com.compomics.dataprovider.view.wizard.panels.processing.ProcessingMethodPanel processingMethodPanel1;
    private javax.swing.ButtonGroup rbInputButtonGroup;
    // End of variables declaration//GEN-END:variables
}
